package com.ztesoft.zsmart.zcm.dialing.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * @author Weiping Ye
 * @version 创建时间：2013-4-9 下午2:58:46
 **/
public final class JsonUtils {
    private static ObjectMapper objectMapper = null;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyyMMddHHmmssS"));
        objectMapper.getDeserializationConfig().withDateFormat(new SimpleDateFormat("yyyyMMddHHmmssS"));
    }

    private JsonUtils() {

    }

    /**
     * json串转为Java对象列表。
     *
     * @param json json串
     * @param clazz Java类
     * @return Java对象列表
     * @throws Exception
     */
    public static <T> List<T> toJavaList(String json, Class<T> clazz) throws IOException {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
    }

    /**
     * 从文件中读取json串，并转为Java对象列表。
     *
     * @param file 文件
     * @param clazz Java类
     * @return Java对象列表
     * @throws Exception
     */
    public static <T> List<T> toJavaList(File file, Class<T> clazz) throws IOException {
        return objectMapper.readValue(file, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
    }

    /**
     * json串转为Java对象。
     *
     * @param json json串
     * @param clazz Java类
     * @return Java对象
     * @throws Exception
     */
    public static <T> T toJava(String json, Class<T> clazz) throws IOException {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return objectMapper.readValue(json, clazz);
    }

    public static <T, V> Map<T, V> toJavaMap(String jsonString, Class<T> keyClass, Class<V> valueClass)
        throws IOException {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        return objectMapper.readValue(jsonString,
            objectMapper.getTypeFactory().constructMapLikeType(Map.class, keyClass, valueClass));
    }
}
